{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "#请先运行此代码\n",
    "from IPython.core.interactiveshell import InteractiveShell\n",
    "InteractiveShell.ast_node_interactivity = \"all\" \n",
    "#这玩意可以让代码块分行输出"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 使用__slots__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 正常情况下，当我们定义了一个class，创建了一个class的实例后，我们可以给该实例绑定任何属性和方法，这就是动态语言的灵活性。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Michael\n"
     ]
    }
   ],
   "source": [
    "class Student(object):\n",
    "    pass\n",
    "\n",
    "s = Student()\n",
    "s.name = 'Michael' # 动态给实例绑定一个属性\n",
    "print(s.name)\n",
    "\n",
    "def set_age(self, age): # 定义一个函数作为实例方法\n",
    "     self.age = age\n",
    "     \n",
    "from types import MethodType\n",
    "s.set_age = MethodType(set_age, s) # 给实例绑定一个方法\n",
    "s.set_age(25) # 调用实例方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 但是，给一个实例绑定的方法，对另一个实例是不起作用的,为了给所有实例都绑定方法，可以给class绑定方法："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Student(object):\n",
    "    pass\n",
    "\n",
    "def set_score(self, score):\n",
    "     self.score = score\n",
    "\n",
    "Student.set_score = set_score"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 给class绑定方法后，所有实例均可调用："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "100"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "text/plain": [
       "99"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s=Student()\n",
    "s2=Student()\n",
    "\n",
    "s.set_score(100)\n",
    "s.score\n",
    "s2.set_score(99)\n",
    "s2.score"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 使用__slots__（中文翻译：插槽）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 如果我们想要限制实例的属性怎么办？比如，只允许对Student实例添加name和age属性。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'Student' object has no attribute 'score'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_13844/3632174701.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      6\u001b[0m \u001b[0ms\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mage\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m25\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      7\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 8\u001b[1;33m \u001b[0ms\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mscore\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m99\u001b[0m \u001b[1;31m# 绑定属性'score'，不在白名单中，不让你绑定，故报错\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m: 'Student' object has no attribute 'score'"
     ]
    }
   ],
   "source": [
    "class Student(object):\n",
    "    __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称\n",
    "    \n",
    "s = Student() # 创建新的实例\n",
    "s.name = 'Michael'\n",
    "s.age = 25\n",
    "\n",
    "s.score = 99 # 绑定属性'score'，不在白名单中，不让你绑定，故报错"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 注意的一点是，__slots__定义的属性仅对当前类实例起作用，对继承的子类是不起作用的："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "class GraduateStudent(Student):\n",
    "     pass\n",
    "\n",
    "g = GraduateStudent()\n",
    "g.score = 9999#随便你绑定"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 除非在子类中也定义__slots__，这样，子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 使用@property"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 有没有既能检查参数，又可以用类似属性这样简单的方式来访问类的变量呢？对于追求完美的Python程序员来说，这是必须要做到的！\n",
    "\n",
    "* 还记得装饰器（decorator）可以给函数动态加上功能吗？对于类的方法，装饰器一样起作用。Python内置的@property装饰器就是负责把一个方法变成属性调用的："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "60"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class Student(object):\n",
    "\n",
    "    @property\n",
    "    def score(self):\n",
    "        return self._score\n",
    "\n",
    "    @score.setter\n",
    "    def score(self, value):\n",
    "        if not isinstance(value, int):\n",
    "            raise ValueError('score must be an integer!')\n",
    "        if value < 0 or value > 100:\n",
    "            raise ValueError('score must between 0 ~ 100!')\n",
    "        self._score = value\n",
    "#@property的实现比较复杂，我们先考察如何使用。把一个getter方法变成属性，只需要加上@property就可以了，此时，\n",
    "# @property本身又创建了另一个装饰器@score.setter，负责把一个setter方法变成属性赋值，于是，我们就拥有一个可控的属性操作：\n",
    "s = Student()\n",
    "s.score = 60 # OK，实际转化为s.set_score(60)\n",
    "s.score # OK，实际转化为s.get_score()\n",
    "#s.score = 9999#太高了，报错了"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 还可以定义只读属性，只定义getter方法，不定义setter方法就是一个只读属性："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "20"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class Student(object):\n",
    "\n",
    "    @property\n",
    "    def birth(self):\n",
    "        return self._birth\n",
    "\n",
    "    @birth.setter\n",
    "    def birth(self, value):\n",
    "        self._birth = value\n",
    "\n",
    "    @property #不定义setter方法，这就是个只读属性，因为age可以根据birth和当前时间计算出来。\n",
    "    def age(self):\n",
    "        return 2015 - self._birth\n",
    "s = Student()\n",
    "s.birth=20\n",
    "s.birth"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 要特别注意：属性的方法名不要和实例变量重名。例如，以下的代码是错误的："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Student(object):\n",
    "\n",
    "    # 方法名称和实例变量均为birth:\n",
    "    @property\n",
    "    def birth(self):\n",
    "        return self.birth#少了个下划线_\n",
    "    s = Student()\n",
    "    s.birth#无限递归，一运行就奔溃了\n",
    "    #这是因为调用s.birth时，首先转换为方法调用，在执行return self.birth时，又视为访问self的属性，于是又转换为方法调用，\n",
    "    # 造成无限递归，最终导致栈溢出报错RecursionError。\n",
    "    #所以正常来说应该是，调用s.birth时，首先转换为方法调用，return self._birth?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 多重继承"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 这边一堆类，他们的分类方法不同"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Animal(object):\n",
    "    pass\n",
    "\n",
    "# 大类:\n",
    "class Mammal(Animal):\n",
    "    pass\n",
    "\n",
    "class Bird(Animal):\n",
    "    pass\n",
    "\n",
    "# 各种动物:\n",
    "class Dog(Mammal):\n",
    "    pass\n",
    "\n",
    "class Bat(Mammal):\n",
    "    pass\n",
    "\n",
    "class Parrot(Bird):\n",
    "    pass\n",
    "\n",
    "class Ostrich(Bird):\n",
    "    pass\n",
    "#能飞还是能跑：\n",
    "class Runnable(object):\n",
    "    def run(self):\n",
    "        print('Running...')\n",
    "\n",
    "class Flyable(object):\n",
    "    def fly(self):\n",
    "        print('Flying...')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Dog(Mammal, Runnable):#显而易见，狗是这样继承的\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Bat(Mammal, Flyable):#显而易见，蝙蝠是这样继承的\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### MixIn"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 就是把Runnable和Flyable改为RunnableMixIn和FlyableMixIn，意义为“混入”，更好理解一点"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Dog(Mammal, RunnableMixIn, CarnivorousMixIn):#比如这样写\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 定制类"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### __str__方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 我们先定义一个Student类，打印一个实例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<__main__.Student object at 0x0000022A72B173D0>\n"
     ]
    }
   ],
   "source": [
    "class Student(object):\n",
    "     def __init__(self, name):\n",
    "         self.name = name\n",
    "\n",
    "print(Student('Michael'))#这玩意打印的不好看"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 怎么才能打印得好看呢？只需要定义好__str__()方法，返回一个好看的字符串就可以了：\n",
    "* 当使用print输出对象的时候，只要自己定义了__str__(self)方法，那么就会打印从在这个方法中return的数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Student object (name: Michael)\n"
     ]
    }
   ],
   "source": [
    "class Student(object):\n",
    "     def __init__(self, name):\n",
    "         self.name = name\n",
    "     def __str__(self):\n",
    "        return 'Student object (name: %s)' % self.name#返回好看滴值\n",
    "\n",
    "print(Student('Michael'))#Michael传入init"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 但是直接敲变量不用print，打印出来的实例还是不好看："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<__main__.Student at 0x22a72b17970>"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = Student('Michael')\n",
    "s"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 这是因为直接显示变量调用的不是__str__()，而是__repr__()，两者的区别是__str__()返回用户看到的字符串，而__repr__()返回程序开发者看到的字符串，也就是说，__repr__()是为调试服务的。\n",
    "* 解决办法是再定义一个__repr__()。但是通常__str__()和__repr__()代码都是一样的，所以，有个偷懒的写法："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Student object (name=Michael)"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class Student(object):\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "    def __str__(self):\n",
    "        return 'Student object (name=%s)' % self.name\n",
    "    __repr__ = __str__\n",
    "\n",
    "s = Student('Michael')\n",
    "s#这样就好看啦"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### __iter__方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 如果一个类想被用于for ... in循环，类似list或tuple那样，就必须实现一个__iter__()方法，该方法返回一个迭代对象，然后，Python的for循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值，直到遇到StopIteration错误时退出循环。\n",
    "\n",
    "* 以斐波那契数列为例，写一个Fib类，可以作用于for循环："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Fib(object):\n",
    "    def __init__(self):\n",
    "        self.a, self.b = 0, 1 # 初始化两个计数器a，b\n",
    "\n",
    "    def __iter__(self):\n",
    "        return self # 实例本身就是迭代对象，故返回自己\n",
    "\n",
    "    def __next__(self):\n",
    "        self.a, self.b = self.b, self.a + self.b # 计算下一个值\n",
    "        if self.a > 100: # 退出循环的条件\n",
    "            raise StopIteration()#抛出此异常\n",
    "        return self.a # 返回下一个值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "1\n",
      "2\n",
      "3\n",
      "5\n",
      "8\n",
      "13\n",
      "21\n",
      "34\n",
      "55\n",
      "89\n"
     ]
    }
   ],
   "source": [
    "for n in Fib():#非常好用\n",
    "   print(n)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### __getitem__方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* Fib实例虽然能作用于for循环，看起来和list有点像，但是，把它当成list来使用还是不行，比如，取第5个元素："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'Fib' object is not subscriptable",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_12504/3213756406.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mFib\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m5\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: 'Fib' object is not subscriptable"
     ]
    }
   ],
   "source": [
    "Fib()[5]#报错了"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 要表现得像list那样按照下标取出元素，需要实现__getitem__()方法："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "89"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class Fib(object):\n",
    "    def __getitem__(self, n):\n",
    "        a, b = 1, 1\n",
    "        for x in range(n):\n",
    "            a, b = b, a + b\n",
    "        return a\n",
    "\n",
    "f = Fib()\n",
    "f[10]#第10项"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 但是list有个神奇的切片方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(5, 6, 7, 8, 9)"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "text/plain": [
       "[5, 6, 7, 8, 9]"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(0,1,2,3,4,5,6,7,8,9,10)[5:10]\n",
    "list(range(100))[5:10]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'slice' object cannot be interpreted as an integer",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_12504/1823681990.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mf\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m5\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;36m10\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;31m#报错咯\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_12504/4105404334.py\u001b[0m in \u001b[0;36m__getitem__\u001b[1;34m(self, n)\u001b[0m\n\u001b[0;32m      2\u001b[0m     \u001b[1;32mdef\u001b[0m \u001b[0m__getitem__\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mn\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      3\u001b[0m         \u001b[0ma\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mb\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m1\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m1\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m         \u001b[1;32mfor\u001b[0m \u001b[0mx\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mn\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      5\u001b[0m             \u001b[0ma\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mb\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mb\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0ma\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mb\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      6\u001b[0m         \u001b[1;32mreturn\u001b[0m \u001b[0ma\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mTypeError\u001b[0m: 'slice' object cannot be interpreted as an integer"
     ]
    }
   ],
   "source": [
    "f[5:10]#报错咯"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 对于Fib却报错。原因是__getitem__()传入的参数可能是一个int，也可能是一个切片对象slice，所以要做判断："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Fib(object):\n",
    "    def __getitem__(self, n):\n",
    "        if isinstance(n, int): # n是索引\n",
    "            a, b = 1, 1\n",
    "            for x in range(n):\n",
    "                a, b = b, a + b\n",
    "            return a\n",
    "        if isinstance(n, slice): # n是切片\n",
    "            start = n.start#例：f[0:5]的0\n",
    "            stop = n.stop#例：f[0:5]的5\n",
    "            if start is None:#例：f[:5]的初始值缺省了，所以得默认为0\n",
    "                start = 0\n",
    "            a, b = 1, 1\n",
    "            L = []\n",
    "            for x in range(stop):\n",
    "                if x >= start:\n",
    "                    L.append(a)\n",
    "                    \n",
    "                a, b = b, a + b\n",
    "            return L"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[2, 3, 5]"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f = Fib()\n",
    "f[2:5]#这样走的就是slice那个分支了，而不是int分支"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 但是没有对step参数作处理，也没有对负数作处理，所以，要正确实现一个__getitem__()还是有很多工作要做的。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]"
      ]
     },
     "execution_count": 68,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f[:10:2]#结果和f[:10]一样的，没有对步长进行处理"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### __getattr__方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'Student' object has no attribute 'score'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_12504/2532537049.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      4\u001b[0m         \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mname\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'Michael'\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      5\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 6\u001b[1;33m \u001b[0ms\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mscore\u001b[0m\u001b[1;31m#没有attribute叫做score的\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m: 'Student' object has no attribute 'score'"
     ]
    }
   ],
   "source": [
    "class Student(object):\n",
    "    \n",
    "    def __init__(self):\n",
    "        self.name = 'Michael'\n",
    "\n",
    "s.score#没有attribute叫做score的"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 所以我们可以这样写"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "99"
      ]
     },
     "execution_count": 72,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class Student(object):\n",
    "\n",
    "    def __init__(self):\n",
    "        self.name = 'Michael'\n",
    "\n",
    "    def __getattr__(self, attr):\n",
    "        if attr=='score':\n",
    "            return 99\n",
    "s=Student()\n",
    "s.score#当调用不存在的属性时，比如score，Python解释器会试图调用__getattr__(self, 'score')来尝试获得属性，这样，我们就有机会返回score的值："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 返回函数也是可以的"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 注意，只有在没有找到属性的情况下，才调用__getattr__，已有的属性，比如name，不会在__getattr__中查找。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "25"
      ]
     },
     "execution_count": 73,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class Student(object):\n",
    "\n",
    "    def __getattr__(self, attr):\n",
    "        if attr=='age':\n",
    "            return lambda: 25\n",
    "\n",
    "s=Student()\n",
    "s.age()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 此外，注意到任意调用如s.abc都会返回None，这是因为我们定义的__getattr__默认返回就是None。要让class只响应特定的几个属性，我们就要按照约定，抛出AttributeError的错误："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<function __main__.Student.__getattr__.<locals>.<lambda>()>"
      ]
     },
     "execution_count": 75,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class Student(object):\n",
    "\n",
    "    def __getattr__(self, attr):\n",
    "        if attr=='age':\n",
    "            return lambda: 25\n",
    "        raise AttributeError('\\'Student\\' object has no attribute \\'%s\\'' % attr)\n",
    "s=Student()\n",
    "s.age"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 利用完全动态的__getattr__，我们可以写出一个链式调用："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "/status/user/timeline/list"
      ]
     },
     "execution_count": 76,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class Chain(object):\n",
    "\n",
    "    def __init__(self, path=''):\n",
    "        self._path = path\n",
    "\n",
    "    def __getattr__(self, path):\n",
    "        return Chain('%s/%s' % (self._path, path))\n",
    "\n",
    "    def __str__(self):\n",
    "        return self._path\n",
    "\n",
    "    __repr__ = __str__\n",
    "\n",
    "Chain().status.user.timeline.list"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## **看不太懂这个** 只看懂7成"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "结果是/users/michael/repos"
      ]
     },
     "execution_count": 99,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class Chain(object):\n",
    "    def __init__(self, path=''):\n",
    "       self.__path = path\n",
    "\n",
    "    def __getattr__(self, path):\n",
    "       return Chain('%s/%s' % (self.__path, path))#这里return的是一个path\n",
    " \n",
    "    def __call__(self, path):\n",
    "       return Chain('%s/%s' % (self.__path, path))#这里实例进行调用，又return一个path\n",
    "\n",
    "    def __str__(self):#用于显示结果的\n",
    "       return \"结果是%s\" %self.__path\n",
    "\n",
    "    __repr__ = __str__\n",
    "\n",
    "#Chain('%s/%s' % (self.__path, path)的作用是把新的path加到原先的path上面，由于这个新path不存在，所以会调用getattr\n",
    "#users('michael')对实例调用，就是对__call__(self, path)调用，return值和上面的__getattr__一个道理\n",
    "Chain().users('michael').repos# /users/michael/repos"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### __call__\n",
    "* 任何类，只需要定义一个__call__()方法，就可以直接对实例进行调用。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "My name is Michael.\n"
     ]
    }
   ],
   "source": [
    "class Student(object):\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "\n",
    "    def __call__(self):\n",
    "        print('My name is %s.' % self.name)\n",
    "        \n",
    "s = Student('Michael')\n",
    "s() # self参数不要传入"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 通过callable()函数，我们就可以判断一个对象是否是“可调用”对象。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "callable(Student('Michael'))\n",
    "callable(max)\n",
    "callable([1, 2, 3])\n",
    "callable(None)\n",
    "callable('str')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 使用枚举类"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 更好的方法是为这样的枚举类型定义一个class类型，然后，每个常量都是class的一个唯一实例。Python提供了Enum类来实现这个功能：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Jan => Month.Jan , 1\n",
      "Feb => Month.Feb , 2\n",
      "Mar => Month.Mar , 3\n",
      "Apr => Month.Apr , 4\n",
      "May => Month.May , 5\n",
      "Jun => Month.Jun , 6\n",
      "Jul => Month.Jul , 7\n",
      "Aug => Month.Aug , 8\n",
      "Sep => Month.Sep , 9\n",
      "Oct => Month.Oct , 10\n",
      "Nov => Month.Nov , 11\n",
      "Dec => Month.Dec , 12\n"
     ]
    }
   ],
   "source": [
    "from enum import Enum\n",
    "\n",
    "theMonth = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))\n",
    "\n",
    "for name, member in theMonth.__members__.items():#枚举他的所有成员\n",
    "    print(name, '=>', member, ',', member.value)#value属性则是自动赋给成员的int常量，默认从1开始计数。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 如果需要更精确地控制枚举类型，可以从Enum派生出自定义类"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "metadata": {},
   "outputs": [],
   "source": [
    "from enum import Enum, unique\n",
    "\n",
    "@unique      #@unique装饰器可以帮助我们检查保证没有重复值\n",
    "class Weekday(Enum):\n",
    "    Sun = 0 # Sun的value被设定为0\n",
    "    Mon = 1\n",
    "    Tue = 2\n",
    "    Wed = 3\n",
    "    Thu = 4\n",
    "    Fri = 5\n",
    "    Sat = 6"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Weekday.Mon\n",
      "Weekday.Tue\n",
      "Weekday.Tue\n",
      "2\n",
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "day1 = Weekday.Mon\n",
    "print(day1)\n",
    "print(Weekday.Tue)\n",
    "print(Weekday['Tue'])\n",
    "print(Weekday.Tue.value)\n",
    "print(day1 == Weekday.Mon)\n",
    "print(day1 == Weekday.Tue)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Weekday.Mon\n",
      "True\n",
      "Sun => Weekday.Sun\n",
      "Mon => Weekday.Mon\n",
      "Tue => Weekday.Tue\n",
      "Wed => Weekday.Wed\n",
      "Thu => Weekday.Thu\n",
      "Fri => Weekday.Fri\n",
      "Sat => Weekday.Sat\n"
     ]
    }
   ],
   "source": [
    "print(Weekday(1))\n",
    "print(day1 == Weekday(1))\n",
    "#Weekday(7)\n",
    "for name, member in Weekday.__members__.items():\n",
    "     print(name, '=>', member)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 使用元类"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 116,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, world.\n",
      "<class 'type'>\n",
      "<class '__main__.Hello'>\n"
     ]
    }
   ],
   "source": [
    "class Hello(object):\n",
    "    def hello(self, name='world'):\n",
    "        print('Hello, %s.' % name)\n",
    "\n",
    "h = Hello()\n",
    "h.hello()\n",
    "\n",
    "print(type(Hello))#Hello是一个class，它的类型就是type\n",
    "print(type(h))#h是一个实例，它的类型就是class Hello"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* type()函数既可以返回一个对象的类型，又可以创建出新的类型，比如，我们可以通过type()函数创建出Hello类，而无需通过class Hello(object)...的定义："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, world.\n",
      "<class 'type'>\n",
      "<class '__main__.Hello'>\n"
     ]
    }
   ],
   "source": [
    "def fn(self, name='world'): # 先定义函数\n",
    "    print('Hello, %s.' % name)\n",
    "\n",
    "Hello = type('Hello', (object,), dict(hello=fn)) # 创建Hello class\n",
    "\n",
    "#和上面代码是一样的\n",
    "h = Hello()\n",
    "h.hello()\n",
    "print(type(Hello))\n",
    "print(type(h))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# **这边先跳过，有需要再来看**"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "2e918aaa81d99c652401bdd1a0c185581595fb477ac919641bd65261b5d7782a"
  },
  "kernelspec": {
   "display_name": "Python 3.9.7 64-bit ('base': conda)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
